package cn.edu.ctbu.service.impl;

import cn.edu.ctbu.DTO.PutUserDTO.PutUserDTO;
import cn.edu.ctbu.VO.LoginVO;
import cn.edu.ctbu.VO.MemberVO;
import cn.edu.ctbu.VO.UserVO;
import cn.edu.ctbu.entity.User;
import cn.edu.ctbu.entity.WXproperties;
import cn.edu.ctbu.mapper.UserMapper;
import cn.edu.ctbu.service.IUserService;
import cn.edu.ctbu.utils.JWTUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    HttpServletRequest httpServletRequest;
    @Override
    public MemberVO member(LocalDate startTime, LocalDate endTime) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(startTime);
        LocalDate newDate=startTime;
        while (!newDate.equals(endTime)){
            newDate=newDate.plusDays(1);
            dateList.add(newDate);
        }
        List<Integer> newMember=new ArrayList<>();
        List<Integer> totalMember=new ArrayList<>();
        for (LocalDate date:dateList){
            LocalDateTime min= LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max=LocalDateTime.of(date,LocalTime.MAX);
            QueryWrapper wrapper1=new QueryWrapper<>().le("create_time",max);
            totalMember.add(list(wrapper1).size());
            QueryWrapper wrapper2=new QueryWrapper<>().ge("create_time",min).le("create_time",max);
            newMember.add(list(wrapper2).size());
        }
        MemberVO vo=MemberVO.builder().dateList(dateList).newMember(newMember).totalMember(totalMember).build();
        return vo;
    }

    @Override
    public UserVO login(String code) {
        Map<String,String>map=new HashMap<>();
        map.put("appid",WXproperties.appid);
        map.put("secret",WXproperties.secret);
        map.put("grant_type",WXproperties.grant_type);
        map.put("js_code",code);

        //发送请求
        String url="https://api.weixin.qq.com/sns/jscode2session?appid={appid}&" +
                "secret={secret}&grant_type={grant_type}&js_code={js_code}";
        RestTemplate restTemplate=new RestTemplate();
        String vo=  restTemplate.getForObject(url, String.class, map);
        LoginVO loginVO = JSON.parseObject(vo, LoginVO.class);
        QueryWrapper wrapper=new QueryWrapper<>().eq("openid",loginVO.getOpenid());
        User user = getOne(wrapper);
        //下发token令牌
        Map<String,Object>claims=new HashMap<>();
        claims.put("openid",user.getOpenid());
        claims.put("id",user.getId());
        String s = JWTUtils.generateJwt(claims);
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        userVO.setToken(s);
        return userVO;
    }

    @Override
    public User get() {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long userid = claims.get("id", Long.class);

        User user = getById(userid);
        return user;
    }

    @Override
    public void putUser(PutUserDTO dto) {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long userid = claims.get("id", Long.class);

        UpdateWrapper wrapper=new UpdateWrapper<>().eq("id",userid);
         if (dto.getNickName()!=null){
             wrapper.set("nick_name",dto.getNickName());
         }
         update(wrapper);
    }
}
